import { useState } from 'react';
import { get as getPath } from 'object-path';
import isEmpty from 'lodash/isEmpty';
import { utils } from 'vv-frontend-components';
import { message } from 'antd';
import groupBy from 'lodash/groupBy';
import moment from 'moment';
import { saveorupdate, employeeDetail, update } from '@/services/Organization/staffmanage';
import { dictionaryList } from '@/services/dictionary';
import { jsonFormWork, jsonFormFamily, jsonFormSchool, jsonFormTrain, jsonFormAward } from '@/pages/InitUser/jsonForm';

const { deepTrim } = utils;
/**
 * 初始化组件状态
 * 一般组件只需要复用状态、逻辑 不需要复用数据，所以在简单的业务页面我放弃了 redux
 */
export const useInit = () => {
    // 表单的默认值
    const [formData, setFormData] = useState({});
    // 表单中的基础字典数据
    const [dictionary, setDictionary] = useState({});
    const [loading, setLoading] = useState(false);
    const [spinning, setSpinning] = useState(false);
    // 切换公司时表单联动需要的id
    const [obaCompanyId, setObaCompanyId] = useState(null);
    const [companyName, setCompanyName] = useState('');
    const [postTypeRemark, setPostTypeRemark] = useState('');
    return {
        formData,
        setFormData,
        dictionary,
        setDictionary,
        loading,
        setLoading,
        obaCompanyId,
        setObaCompanyId,
        spinning,
        setSpinning,
        companyName,
        setCompanyName,
        postTypeRemark,
        setPostTypeRemark
    };
};

export const handleSubmit = props => {
    const { form, userCode, formData, callback, companyName, setLoading, from } = props;
    /**
     * 提交时处理一些特殊字段
     * select 未选时 value 只能接受undefined才能正常显示 placeholder,传服务端需要转为null...
     */
    form.validateFieldsAndScroll(async (err, value) => {
        if (!err) {
            // 家庭数据
            const familyData = [];
            if (value.familyKeys) {
                value.familyKeys.forEach(key => {
                    const obj = {};
                    jsonFormFamily.forEach(item => {
                        obj[item.fileName.replace('family_', '')] = value[`${item.fileName}_${key}`];
                    });
                    obj.areaCode = value[`family_areaCode_${key}`]; // 因为这个区号不在判断范围内，所以单独添加
                    obj.userCode = formData.userCode;
                    obj.id = (formData.familyDTOList[key] && formData.familyDTOList[key].id) || null;
                    obj.deleteFlag = obj.id && value.removeFamilyIds.includes(obj.id) ? 1 : 0;
                    if (Object.keys(obj).length > 0) {
                        familyData.push(obj);
                    }
                });
            }

            // 工作数据
            const workData = [];
            if (value.workKeys) {
                value.workKeys.forEach(key => {
                    const obj = {};
                    jsonFormWork.forEach(item => {
                        obj.userCode = formData.userCode;
                        obj.id = (formData.workDTOList[key] && formData.workDTOList[key].id) || null;
                        if (value[`${item.fileName}_${key}`]) {
                            obj.deleteFlag = obj.id && value.removeWorkIds.includes(obj.id) ? 1 : 0;
                            if (obj.deleteFlag !== 1) {
                                // 时间字段需要特殊处理
                                if (
                                    item.fileName === 'work_startTime' &&
                                    value[`${item.fileName}_${key}`] &&
                                    value[`${item.fileName}_${key}`].length > 0
                                ) {
                                    const startTime = value[`${item.fileName}_${key}`][0];
                                    const endTime = value[`${item.fileName}_${key}`][1];

                                    obj.startTime = startTime ? moment(startTime).format('YYYY-MM-01') : '';
                                    obj.endTime = endTime ? moment(endTime).format('YYYY-MM-01') : '';
                                } else {
                                    obj[item.fileName.replace('work_', '')] = value[`${item.fileName}_${key}`];
                                }
                            }
                        }
                    });
                    obj.areaCode = value[`work_areaCode_${key}`]; // 因为这个区号不在判断范围内，所以单独添加
                    if (Object.keys(obj).length > 0) {
                        workData.push(obj);
                    }
                });
            }

            // 教育经历
            const schoolData = [];
            if (value.schoolKeys) {
                value.schoolKeys.forEach(key => {
                    const obj = {};
                    jsonFormSchool.forEach(item => {
                        obj.id = (formData.schoolDTOList[key] && formData.schoolDTOList[key].id) || null;
                        obj.userCode = formData.userCode;
                        obj.deleteFlag = obj.id && value.removeSchoolIds.includes(obj.id) ? 1 : 0;
                        if (obj.deleteFlag !== 1) {
                            // 时间字段需要特殊处理
                            if (item.fileName === 'school_startTime') {
                                obj.startTime = moment(value[`${item.fileName}_${key}`][0]).format('YYYY-MM-01');
                                obj.endTime = moment(value[`${item.fileName}_${key}`][1]).format('YYYY-MM-01');
                            } else {
                                obj[item.fileName.replace('school_', '')] = value[`${item.fileName}_${key}`];
                            }
                        }
                    });
                    if (Object.keys(obj).length > 0) {
                        schoolData.push(obj);
                    }
                });
            }

            // 培训经历
            const trainData = [];
            if (value.trainKeys) {
                value.trainKeys.forEach(key => {
                    const obj = {};
                    jsonFormTrain.forEach(item => {
                        obj.userCode = formData.userCode;
                        obj.id = (formData.trainDTOList[key] && formData.trainDTOList[key].id) || null;
                        obj.deleteFlag = obj.id && value.removeTrainIds.includes(obj.id) ? 1 : 0;
                        if (value[`${item.fileName}_${key}`]) {
                            if (obj.deleteFlag !== 1) {
                                // 时间字段需要特殊处理
                                if (
                                    item.fileName === 'train_startTime' &&
                                    value[`${item.fileName}_${key}`] &&
                                    value[`${item.fileName}_${key}`].length > 0
                                ) {
                                    const startTime = value[`${item.fileName}_${key}`][0];
                                    const endTime = value[`${item.fileName}_${key}`][1];

                                    obj.startTime = startTime ? moment(startTime).format('YYYY-MM-01') : '';
                                    obj.endTime = endTime ? moment(endTime).format('YYYY-MM-01') : '';
                                } else {
                                    obj[item.fileName.replace('train_', '')] = value[`${item.fileName}_${key}`];
                                }
                            }
                        }
                    });
                    if (Object.keys(obj).length > 0) {
                        const { userCode: uc, id, deleteFlag, ...reset } = obj;
                        if (obj.id === null && Object.keys(reset).length === 0) {
                            return;
                        }
                        trainData.push(obj);
                    }
                });
            }

            // 获奖记录
            const awardData = [];
            if (value.awardKeys) {
                value.awardKeys.forEach(key => {
                    const obj = {};
                    jsonFormAward.forEach(item => {
                        obj.userCode = formData.userCode;
                        obj.id = (formData.awardDTOList[key] && formData.awardDTOList[key].id) || null;
                        obj.deleteFlag = obj.id && value.removeAwardIds.includes(obj.id) ? 1 : 0;
                        if (value[`${item.fileName}_${key}`]) {
                            if (obj.deleteFlag !== 1) {
                                // 时间字段需要特殊处理
                                if (item.fileName === 'award_awardTime' && value[`${item.fileName}_${key}`]) {
                                    obj.awardTime = moment(value[`${item.fileName}_${key}`]).format(
                                        'YYYY-MM-DD 00:00:00'
                                    );
                                } else {
                                    obj[item.fileName.replace('award_', '')] = value[`${item.fileName}_${key}`];
                                }
                            }
                        }
                    });
                    if (Object.keys(obj).length > 0) {
                        const { userCode: uc, id, deleteFlag, ...reset } = obj;
                        if (obj.id === null && Object.keys(reset).length === 0) {
                            return;
                        }
                        awardData.push(obj);
                    }
                });
            }

            const params = deepTrim({
                userName: getPath(value, 'userName', null),
                employeeName: getPath(value, 'employeeName', null),
                email: getPath(value, 'email', null),
                areaCode: getPath(value, 'mobile.areaCode', null),
                mobile: getPath(value, 'mobile.mobile', null),
                userNo: getPath(value, 'userNo', null),
                companyId: getPath(value, 'companyId', null),
                departmentId: getPath(value, 'departmentId', null),
                postId: getPath(value, 'postId', null),
                roles: getPath(value, 'roles', null),
                employeeRank: getPath(value, 'employeeRank', null),
                jobDescriptions: getPath(value, 'jobDescriptions', null),
                jobLabel: getPath(value, 'jobLabel', null),
                highestDegree: getPath(value, 'highestDegree', null),
                // graduateSchool: getPath(value, 'graduateSchool', null),
                // major: getPath(value, 'major', null),
                certificate: getPath(value, 'certificate', null),
                sex: getPath(value, 'sex', null),
                nationalArea: getPath(value, 'nationalArea', null),
                address: getPath(value, 'address', null),
                detailAddress: getPath(value, 'detailAddress', null),
                emergencyContact: getPath(value, 'emergencyContact', null),
                emergencyRelationship: getPath(value, 'emergencyRelationship', null),
                emergencyAreaCode: getPath(value, 'emergencyAreaCode', null),
                emergencyTelephone: getPath(value, 'emergencyTelephone', null),
                birthday: isEmpty(value.birthday) ? '' : value.birthday.format('YYYY-MM-DD'),
                timeOfEntry: isEmpty(value.timeOfEntry) ? '' : value.timeOfEntry.format('YYYY-MM-DD'),
                firstHouseholdType: getPath(value, 'firstHouseholdType', null),
                secondHouseholdType: getPath(value, 'secondHouseholdType', null),
                // 表单二
                familyDTOList: familyData,
                workExperience: getPath(value, 'workExperience', 0),
                workDTOList: value.workExperience === 0 ? [] : workData,
                // 表单三
                schoolDTOList: schoolData,
                trainDTOList: trainData,

                // 表单四
                awardDTOList: awardData,

                companyName: companyName || formData.companyName,
                id: userCode ? formData.id : null,
                orgUserId: userCode ? formData.orgUserId : null,
                orgUserSchoolId: userCode ? formData.orgUserSchoolId : null,
                agree: '1',
                operateWay: from === 'msg' ? '3' : '1',
                userCode,
                idCard: formData.idCard,
                postCode: formData.postCode,
                workYear: formData.workYear,
                workMonth: formData.workMonth,
                workNature: formData.workNature,
                tryDuration: formData.tryDuration
            });
            console.log(params, 'params');
            setLoading(true);
            let result;
            if (userCode) {
                result = await update(params);
            } else {
                result = await saveorupdate(params);
            }
            setLoading(false);
            if (result.code === 10000) {
                callback();
            } else {
                callback(result.msg);
                message.error(result.msg);
            }
        }
    });
};
/**
 * 获取一些基础的字典
 * @param {*} {setDictionary, setSpinning}
 */
export const searchDic = async props => {
    const { setDictionary, setSpinning } = props;
    setSpinning(true);
    const result = await dictionaryList({
        // 字典code集合 默认拉取页面依赖的字典数据
        codes: [
            'agreeType',
            'sexType',
            'emergencyRelationship',
            'workMonth',
            'workYear',
            'liveTogether',
            'workExperience',
            'household',
            'academicYear',
            'industryType'
        ],
        parentId: null
    });
    setSpinning(false);
    if (result.code === 10000) {
        setDictionary(groupBy(result.data, 'code'));
    }
};
/**
 * 获取表单默认值
 * @param {*} {userCode, setObaCompanyId, setPostTypeRemark, setFormData, setSpinning}
 */
export const getFormData = async props => {
    const { userCode, setObaCompanyId, setPostTypeRemark, setFormData, setSpinning } = props;
    setSpinning(true);
    const result = await employeeDetail({ userCode });
    setSpinning(false);
    if (result.code === 10000) {
        setFormData(result.data);
        setObaCompanyId(result.data.companyId);
        setPostTypeRemark(result.data.postTypeRemark);
    } else {
        message.error(result.msg);
    }
};
